import logging
from PyQt5.QtWidgets import (QDialog, QTabWidget, QVBoxLayout, QHBoxLayout, 
                            QLabel, QLineEdit, QCheckBox, QSpinBox, QDoubleSpinBox,
                            QPushButton, QGroupBox, QFormLayout, QComboBox, QWidget,
                            QMessageBox, QTextEdit, QApplication)
from voice_assistant.config_manager import config_manager
from voice_assistant.my_config import SETTING_STYLE

logger = logging.getLogger("ConfigDialog")

class ConfigDialog(QDialog):
    """配置设置对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("语音助手设置")
        self.resize(500, 400)
        
        # 设置对话框的默认样式，确保不受外部样式影响
        self.setStyleSheet(SETTING_STYLE)
        
        # 创建主布局
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)
        
        # 创建选项卡
        self.tab_widget = QTabWidget()
        self.tab_widget.setStyleSheet("")  # 确保选项卡不受外部样式影响
        main_layout.addWidget(self.tab_widget)
        
        # 创建各个选项卡
        self.create_general_tab()
        self.create_audio_tab()
        self.create_server_tab()
        self.create_ai_tab()
        self.create_ui_tab()
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        main_layout.addLayout(button_layout)
        
        # 添加按钮
        self.save_button = QPushButton("保存")
        self.save_button.clicked.connect(self.save_config)
        
        self.cancel_button = QPushButton("取消")
        self.cancel_button.clicked.connect(self.reject)
        
        self.reset_button = QPushButton("恢复默认")
        self.reset_button.clicked.connect(self.reset_to_default)
        
        button_layout.addWidget(self.reset_button)
        button_layout.addStretch()
        button_layout.addWidget(self.cancel_button)
        button_layout.addWidget(self.save_button)
        
        # 加载当前配置
        self.load_config()
    
    def create_general_tab(self):
        """创建常规设置选项卡"""
        tab = QWidget()
        layout = QVBoxLayout()
        tab.setLayout(layout)
        
        # 应用设置组
        app_group = QGroupBox("应用设置")
        app_layout = QFormLayout()
        app_group.setLayout(app_layout)
        
        self.app_name = QLineEdit()
        app_layout.addRow("应用名称:", self.app_name)
        
        self.app_version = QLineEdit()
        self.app_version.setReadOnly(True)  # 版本号不可编辑
        app_layout.addRow("版本:", self.app_version)
        
        self.app_debug = QCheckBox("启用调试模式")
        app_layout.addRow("调试:", self.app_debug)
        
        # 唤醒词设置
        wake_group = QGroupBox("唤醒词设置")
        wake_layout = QVBoxLayout()
        wake_group.setLayout(wake_layout)
        
        self.wake_words = QLineEdit()
        wake_layout.addWidget(QLabel("唤醒词列表 (用逗号分隔):"))
        wake_layout.addWidget(self.wake_words)
        
        # 添加到主布局
        layout.addWidget(app_group)
        layout.addWidget(wake_group)
        layout.addStretch()
        
        self.tab_widget.addTab(tab, "常规")
    
    def create_audio_tab(self):
        """创建音频设置选项卡"""
        tab = QWidget()
        layout = QFormLayout()
        tab.setLayout(layout)
        
        self.sample_rate = QSpinBox()
        self.sample_rate.setRange(8000, 48000)
        self.sample_rate.setSingleStep(1000)
        layout.addRow("采样率:", self.sample_rate)
        
        self.channels = QSpinBox()
        self.channels.setRange(1, 2)
        layout.addRow("声道数:", self.channels)
        
        self.chunk_size = QSpinBox()
        self.chunk_size.setRange(256, 4096)
        self.chunk_size.setSingleStep(256)
        layout.addRow("块大小:", self.chunk_size)
        
        self.silence_threshold = QSpinBox()
        self.silence_threshold.setRange(100, 5000)
        self.silence_threshold.setSingleStep(100)
        layout.addRow("静音阈值:", self.silence_threshold)
        
        self.max_silence_frames = QSpinBox()
        self.max_silence_frames.setRange(10, 500)
        self.max_silence_frames.setSingleStep(10)
        layout.addRow("最大静音帧数:", self.max_silence_frames)
        
        self.tab_widget.addTab(tab, "音频")
    
    def create_server_tab(self):
        """创建服务器设置选项卡"""
        tab = QWidget()
        layout = QFormLayout()
        tab.setLayout(layout)
        
        self.ws_url = QLineEdit()
        layout.addRow("WebSocket URL:", self.ws_url)
        
        self.flask_url = QLineEdit()
        layout.addRow("Flask URL:", self.flask_url)
        
        self.reconnect_base_delay = QDoubleSpinBox()
        self.reconnect_base_delay.setRange(0.1, 10.0)
        self.reconnect_base_delay.setSingleStep(0.1)
        layout.addRow("重连基础延迟(秒):", self.reconnect_base_delay)
        
        self.max_reconnect_delay = QDoubleSpinBox()
        self.max_reconnect_delay.setRange(1.0, 300.0)
        self.max_reconnect_delay.setSingleStep(1.0)
        layout.addRow("最大重连延迟(秒):", self.max_reconnect_delay)
        
        self.tab_widget.addTab(tab, "服务器")
    
    def create_ai_tab(self):
        """创建AI设置选项卡"""
        tab = QWidget()
        layout = QVBoxLayout()
        tab.setLayout(layout)
        
        # 基本设置
        basic_group = QGroupBox("基本设置")
        basic_layout = QFormLayout()
        basic_group.setLayout(basic_layout)
        
        self.ai_model = QComboBox()
        self.ai_model.addItems(["gemma3:4b", "deepseek-r1:1.5b", "llama3.2"])
        basic_layout.addRow("AI模型:", self.ai_model)
        
        self.ai_url = QLineEdit()
        basic_layout.addRow("API URL:", self.ai_url)
        
        # 添加PROMPT_CMD设置
        self.prompt_cmd = QTextEdit()
        self.prompt_cmd.setMinimumHeight(100)
        basic_layout.addRow("指令提示词:", self.prompt_cmd)
        
        # 参数设置
        params_group = QGroupBox("模型参数")
        params_layout = QFormLayout()
        params_group.setLayout(params_layout)
        
        self.temperature = QDoubleSpinBox()
        self.temperature.setRange(0.0, 2.0)
        self.temperature.setSingleStep(0.1)
        params_layout.addRow("温度:", self.temperature)
        
        self.top_p = QDoubleSpinBox()
        self.top_p.setRange(0.0, 1.0)
        self.top_p.setSingleStep(0.05)
        params_layout.addRow("Top P:", self.top_p)
        
        self.top_k = QSpinBox()
        self.top_k.setRange(1, 100)
        params_layout.addRow("Top K:", self.top_k)
        
        self.num_predict = QSpinBox()
        self.num_predict.setRange(1, 2048)
        self.num_predict.setSingleStep(32)
        params_layout.addRow("生成长度:", self.num_predict)
        
        self.num_ctx = QSpinBox()
        self.num_ctx.setRange(512, 8192)
        self.num_ctx.setSingleStep(512)
        params_layout.addRow("上下文长度:", self.num_ctx)
        
        self.num_gpu = QSpinBox()
        self.num_gpu.setRange(1, 100)
        params_layout.addRow("GPU层数:", self.num_gpu)
        
        self.num_thread = QSpinBox()
        self.num_thread.setRange(1, 32)
        params_layout.addRow("线程数:", self.num_thread)
        
        # 添加到主布局
        layout.addWidget(basic_group)
        layout.addWidget(params_group)
        
        self.tab_widget.addTab(tab, "AI设置")
    
    def create_ui_tab(self):
        """创建UI设置选项卡"""
        tab = QWidget()
        layout = QFormLayout()
        tab.setLayout(layout)
        
        self.always_on_top = QCheckBox()
        layout.addRow("窗口置顶:", self.always_on_top)
        
        self.opacity = QDoubleSpinBox()
        self.opacity.setRange(0.1, 1.0)
        self.opacity.setSingleStep(0.05)
        layout.addRow("窗口透明度:", self.opacity)
        
        self.theme = QComboBox()
        self.theme.addItems(["light", "dark"])
        layout.addRow("主题:", self.theme)
        
        self.tab_widget.addTab(tab, "界面")
    
    def load_config(self):
        """加载当前配置到界面"""
        # 常规设置
        self.app_name.setText(config_manager.get("app.name"))
        self.app_version.setText(config_manager.get("app.version"))
        self.app_debug.setChecked(config_manager.get("app.debug"))
        
        wake_words = config_manager.get("wake_words")
        self.wake_words.setText(", ".join(wake_words))
        
        # 音频设置
        self.sample_rate.setValue(config_manager.get("audio.sample_rate"))
        self.channels.setValue(config_manager.get("audio.channels"))
        self.chunk_size.setValue(config_manager.get("audio.chunk_size"))
        self.silence_threshold.setValue(config_manager.get("audio.silence_threshold"))
        self.max_silence_frames.setValue(config_manager.get("audio.max_silence_frames"))
        
        # 服务器设置
        self.ws_url.setText(config_manager.get("server.ws_url"))
        self.flask_url.setText(config_manager.get("server.flask_url"))
        self.reconnect_base_delay.setValue(config_manager.get("server.reconnect_base_delay"))
        self.max_reconnect_delay.setValue(config_manager.get("server.max_reconnect_delay"))
        
        # AI设置
        model = config_manager.get("ai.model")
        index = self.ai_model.findText(model)
        if index >= 0:
            self.ai_model.setCurrentIndex(index)
        
        self.ai_url.setText(config_manager.get("ai.url"))
        
        # 加载PROMPT_CMD
        self.prompt_cmd.setText(config_manager.get("ai.prompt_cmd"))
        
        # AI参数
        self.temperature.setValue(config_manager.get("ai.params.temperature"))
        self.top_p.setValue(config_manager.get("ai.params.top_p"))
        self.top_k.setValue(config_manager.get("ai.params.top_k"))
        self.num_predict.setValue(config_manager.get("ai.params.num_predict"))
        self.num_ctx.setValue(config_manager.get("ai.params.num_ctx"))
        self.num_gpu.setValue(config_manager.get("ai.params.num_gpu"))
        self.num_thread.setValue(config_manager.get("ai.params.num_thread"))
        
        # UI设置
        self.always_on_top.setChecked(config_manager.get("ui.always_on_top"))
        self.opacity.setValue(config_manager.get("ui.opacity"))
        
        theme = config_manager.get("ui.theme")
        index = self.theme.findText(theme)
        if index >= 0:
            self.theme.setCurrentIndex(index)
    
    def save_config(self):
        """保存配置"""
        try:
            # 常规设置
            config_manager.set("app.name", self.app_name.text())
            config_manager.set("app.debug", self.app_debug.isChecked())
            
            # 处理唤醒词
            wake_words = [word.strip() for word in self.wake_words.text().split(",") if word.strip()]
            config_manager.set("wake_words", wake_words)
            
            # 音频设置
            config_manager.set("audio.sample_rate", self.sample_rate.value())
            config_manager.set("audio.channels", self.channels.value())
            config_manager.set("audio.chunk_size", self.chunk_size.value())
            config_manager.set("audio.silence_threshold", self.silence_threshold.value())
            config_manager.set("audio.max_silence_frames", self.max_silence_frames.value())
            
            # 服务器设置
            config_manager.set("server.ws_url", self.ws_url.text())
            config_manager.set("server.flask_url", self.flask_url.text())
            config_manager.set("server.reconnect_base_delay", self.reconnect_base_delay.value())
            config_manager.set("server.max_reconnect_delay", self.max_reconnect_delay.value())
            
            # AI设置
            config_manager.set("ai.model", self.ai_model.currentText())
            config_manager.set("ai.url", self.ai_url.text())
            config_manager.set("ai.prompt_cmd", self.prompt_cmd.toPlainText())
            
            # AI参数
            config_manager.set("ai.params.temperature", self.temperature.value())
            config_manager.set("ai.params.top_p", self.top_p.value())
            config_manager.set("ai.params.top_k", self.top_k.value())
            config_manager.set("ai.params.num_predict", self.num_predict.value())
            config_manager.set("ai.params.num_ctx", self.num_ctx.value())
            config_manager.set("ai.params.num_gpu", self.num_gpu.value())
            config_manager.set("ai.params.num_thread", self.num_thread.value())
            
            # UI设置
            config_manager.set("ui.always_on_top", self.always_on_top.isChecked())
            config_manager.set("ui.opacity", self.opacity.value())
            config_manager.set("ui.theme", self.theme.currentText())
            
            # 保存到文件
            if config_manager.save():
                QMessageBox.information(self, "保存成功", "配置已成功保存")
                # 使用 done 方法而不是 accept，避免程序退出
                self.done(QDialog.Accepted)
            else:
                QMessageBox.warning(self, "保存失败", "配置保存失败，请检查文件权限")
        
        except Exception as e:
            logger.error(f"保存配置时出错: {str(e)}")
            QMessageBox.critical(self, "错误", f"保存配置时出错: {str(e)}")
    
    def reset_to_default(self):
        """重置为默认配置"""
        reply = QMessageBox.question(
            self, "确认重置", 
            "确定要重置所有设置到默认值吗？此操作不可撤销。",
            QMessageBox.Yes | QMessageBox.No, 
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 重置配置
            config_manager.config = config_manager.DEFAULT_CONFIG.copy()
            # 重新加载界面
            self.load_config()
            QMessageBox.information(self, "重置完成", "所有设置已重置为默认值")

def show_config_dialog(parent=None):
    """显示配置对话框"""
    # 创建对话框前，确保样式隔离
    app = QApplication.instance()
    old_style = ""
    if app:
        old_style = app.styleSheet()
        # 临时清除全局样式
        app.setStyleSheet("")
    
    # 创建并显示对话框
    dialog = ConfigDialog(parent)
    # 确保对话框使用默认样式
    dialog.setStyleSheet("")
    
    # 执行对话框
    result = dialog.exec_()
    
    # 恢复原来的全局样式
    if app:
        app.setStyleSheet(old_style)
    
    # 返回结果但不影响主程序运行
    return result